<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发票代码" prop="invoiceCode">
        <el-input
          v-model="queryParams.invoiceCode"
          placeholder="请输入发票代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票号码" prop="invoiceNumber">
        <el-input
          v-model="queryParams.invoiceNumber"
          placeholder="请输入发票号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购买方名称" prop="buyerName">
        <el-input
          v-model="queryParams.buyerName"
          placeholder="请输入购买方名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="已开具" value="已开具" />
          <el-option label="已撤销" value="已撤销" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleDownload"
          v-hasPermi="['fiscale:tax:issuedInvoice:download']"
        >下载发票</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="invoiceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发票代码" align="center" prop="invoiceCode" />
      <el-table-column label="发票号码" align="center" prop="invoiceNumber" />
      <el-table-column label="购买方名称" align="center" prop="buyerName" />
      <el-table-column label="销售方名称" align="center" prop="sellerName" />
      <el-table-column label="价税合计" align="center" prop="totalAmount" />
      <el-table-column label="税额" align="center" prop="taxAmount" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '已开具'" type="success">{{ scope.row.status }}</el-tag>
          <el-tag v-else-if="scope.row.status === '已撤销'" type="danger">{{ scope.row.status }}</el-tag>
          <el-tag v-else>{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['fiscale:tax:issuedInvoice:view']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleRevoke(scope.row)"
            v-if="scope.row.status === '已开具'"
            v-hasPermi="['fiscale:tax:issuedInvoice:revoke']"
          >撤销</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleReissue(scope.row)"
            v-if="scope.row.status === '已撤销'"
            v-hasPermi="['fiscale:tax:issuedInvoice:reissue']"
          >重新开具</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 发票详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票代码：">{{ form.invoiceCode }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票号码：">{{ form.invoiceNumber }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态：">
              <el-tag v-if="form.status === '已开具'" type="success">{{ form.status }}</el-tag>
              <el-tag v-else-if="form.status === '已撤销'" type="danger">{{ form.status }}</el-tag>
              <el-tag v-else>{{ form.status }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="购买方名称：">{{ form.buyerName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售方名称：">{{ form.sellerName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间：">{{ form.createTime }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="价税合计：">{{ form.totalAmount }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税额：">{{ form.taxAmount }}</el-form-item>
          </el-col>
        </el-row>
        
        <!-- 发票明细 -->
        <el-divider content-position="center">发票明细</el-divider>
        <el-table :data="form.invoiceItems" style="margin-bottom: 20px;">
          <el-table-column label="商品名称" align="center" prop="goodsName" />
          <el-table-column label="数量" align="center" prop="quantity" />
          <el-table-column label="单价" align="center" prop="unitPrice" />
          <el-table-column label="金额" align="center" prop="amount" />
          <el-table-column label="税率" align="center" prop="taxRate" />
          <el-table-column label="税额" align="center" prop="taxAmount" />
        </el-table>
        
        <!-- 关联报关单 -->
        <el-divider content-position="center">关联报关单</el-divider>
        <el-table :data="declarationList" style="margin-bottom: 20px;">
          <el-table-column label="报关单号" align="center" prop="declarationNo" />
          <el-table-column label="预录入编号" align="center" prop="preEntryNo" />
          <el-table-column label="报关类型" align="center" prop="declarationType" />
          <el-table-column label="贸易方式" align="center" prop="tradeMode" />
          <el-table-column label="运输方式" align="center" prop="transportMode" />
          <el-table-column label="报关状态" align="center" prop="customsStatus" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
        <el-button
          type="warning"
          @click="handleDownload"
          v-if="form.status === '已开具'"
          v-hasPermi="['fiscale:tax:issuedInvoice:download']"
        >下载发票</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listIssuedInvoices, getIssuedInvoice, revokeInvoice, reissueInvoice } from "@/api/fiscale/tax";

export default {
  name: "IssuedInvoice",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 已开发票表格数据
      invoiceList: [],
      // 关联报关单数据
      declarationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invoiceCode: null,
        invoiceNumber: null,
        buyerName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询已开发票列表 */
    getList() {
      this.loading = true;
      listIssuedInvoices(this.queryParams).then(response => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.invoiceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      getIssuedInvoice(row.invoiceId).then(response => {
        this.form = response.data;
        // 获取关联的报关单信息
        if (this.form.declarationIds && this.form.declarationIds.length > 0) {
          // 这里应该调用获取报关单详情的接口
          // 暂时用模拟数据
          this.declarationList = [
            {
              declarationNo: "BG20250919001",
              preEntryNo: "YLR20250919001",
              declarationType: "出口报关",
              tradeMode: "一般贸易",
              transportMode: "海运",
              customsStatus: "已开票"
            }
          ];
        } else {
          this.declarationList = [];
        }
        this.open = true;
        this.title = "发票详情";
      });
    },
    /** 撤销按钮操作 */
    handleRevoke(row) {
      this.$confirm('是否确认撤销发票编号为"' + row.invoiceNumber + '"的发票?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return revokeInvoice(row.invoiceId);
      }).then(() => {
        this.getList();
        this.$message({
          message: "撤销成功",
          type: "success"
        });
      }).catch(() => {});
    },
    /** 重新开具按钮操作 */
    handleReissue(row) {
      this.$confirm('是否确认重新开具发票编号为"' + row.invoiceNumber + '"的发票?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return reissueInvoice(row.invoiceId);
      }).then(() => {
        this.getList();
        this.$message({
          message: "重新开具成功",
          type: "success"
        });
      }).catch(() => {});
    },
    /** 下载发票按钮操作 */
    handleDownload() {
      // 这里应该调用下载发票的接口
      this.$message({
        message: "下载发票功能待实现",
        type: "warning"
      });
    }
  }
};
</script>